import fp from 'fastify-plugin';
import { ZodError } from 'zod';

export enum ERROR_CODE {
    NO_AUTHORIZATION = 10000
};

export class CustomError extends Error {
    constructor(public message: string, public errCode: ERROR_CODE) {
        super(message);
    }
}

export default fp(function (fastify, opts, done) {
    fastify.setErrorHandler((error, request, reply) => {
        if (error instanceof ZodError) {
            reply.status(400).send({
                code: 400,
                error: error.issues,
            });
            return;
        }

        if (error instanceof CustomError) {
            reply.status(400).send({
                code: error.errCode,
                error: error.message,
            });
            return;
        }

        reply.status(500).send({
            code: 500,
            error: error.message,
            message: 'System Exception',
        });
    });

    done();
});